package com.example.mybatisplus.controller;

import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.model.domain.ConsultMerge;
import com.example.mybatisplus.model.domain.SingleTime;
import com.example.mybatisplus.model.domain.User;
import com.example.mybatisplus.service.ConsultMergeService;
import com.example.mybatisplus.service.SingleTimeService;
import com.example.mybatisplus.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 *  前端控制器
 *
 *
 * @author lxp
 * @since 2022-05-29
 * @version v1.0
 */
@RestController
@RequestMapping("/api/consultMerge")
public class ConsultMergeController {

    private final Logger logger = LoggerFactory.getLogger( ConsultMergeController.class );

    @Autowired
    private ConsultMergeService consultMergeService;

    @Autowired
    private UserService userService;

    @Autowired
    private SingleTimeService singleTimeService;

    @GetMapping("")
    public JsonResponse show(){
        List<ConsultMerge> consultMerges = consultMergeService.list();
        List<User> users = userService.list();
        List<SingleTime> singleTimes = singleTimeService.list();
        List<Map<String,Object>> res = new ArrayList<>();
        for(ConsultMerge c : consultMerges){
            Map<String,Object> temp = new HashMap<>();
            temp.put("consult",c);
            for(User u : users){
                if(c.getTeaId().toString().equals(u.getId().toString())){
                    temp.put("teacherName",u.getStuName());
                }
                if(c.getStuId().toString().equals(u.getId().toString())){
                    temp.put("stuName",u.getStuName());
                }
            }
            for(SingleTime s : singleTimes){
                if(c.getTimeId().toString().equals(s.getId().toString())){
                    temp.put("time",s.getWeakDay()+s.getTimeDay());
                }
            }
            res.add(temp);
        }
        return JsonResponse.success(res).setMessage("查询咨询信息成功");
    }

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        ConsultMerge  consultMerge =  consultMergeService.getById(id);
        return JsonResponse.success(consultMerge);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        consultMergeService.deletebyId(id);
        return JsonResponse.success("删除成功");
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateConsultMerge(ConsultMerge  consultMerge) throws Exception {
        consultMergeService.updateById(consultMerge);
        return JsonResponse.success(null);
    }


    /**
     * 描述： 查询所有咨询汇总记录
     */
    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getall()throws Exception {
        List<ConsultMerge> consultMerges =  consultMergeService.getall();
        List<Map<String,String>> list=new ArrayList<>();
        for (ConsultMerge consultMerge:consultMerges){
            list.add(packgeConsultMerge(consultMerge));
        }
        return JsonResponse.success(list);
    }


    /**
    * 描述:创建ConsultMerge
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(ConsultMerge  consultMerge) throws Exception {
        consultMergeService.save(consultMerge);
        return JsonResponse.success(null);
    }

    /**
     * 描述:新增咨询,若传过来的咨询的时间，咨询师，咨询时间段皆不为空，自动生成8条默认记录，若为空，则在心理助理选择时间和咨询师后，点击修改后自动生成8条记录+++
     *
     */
    @RequestMapping(value = "/addConsult", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse insert(@RequestBody ConsultMerge  consultMerge) throws Exception {
        Long stu_id = consultMerge.getStuId();
        System.out.println(stu_id);
        boolean isExist = consultMergeService.queryConsult(consultMerge.getStuId());
        if(isExist){
            return JsonResponse.failure("已存在咨询");
        }
        else {
            consultMergeService.addConsult(consultMerge);
            return JsonResponse.success("成功");
        }
    }

    /***
     *描述：修改咨询的时间，咨询师，咨询时间段（这三个不为空），并自动生成咨询记录表里的8条数据。
     */
    @RequestMapping(value = "/a/updateconsultMerge", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateconsultMerge(@RequestBody ConsultMerge consultMerge)throws Exception{
        String message= consultMergeService.updateconsultMerge(consultMerge);
        if(message!="更新成功"){
            return JsonResponse.failure(message);
        }
        else return JsonResponse.success().setMessage(message);
    }



    public Map<String,String> packgeConsultMerge(ConsultMerge consultMerge){
        Map<String,String> map=new HashMap<String, String>();
        try {
            map.put("stu_name",userService.getById(consultMerge.getStuId()).getStuName());
            map.put("tea_name",userService.getConsultantById(consultMerge.getTeaId()).getStuName());
            map.put("week_name",singleTimeService.getById(consultMerge.getTimeId()).getWeakDay());
            map.put("detail_time",singleTimeService.getById(consultMerge.getTimeId()).getTimeDay());
            map.put("id",consultMerge.getId().toString());
            map.put("teaId",consultMerge.getTeaId().toString());
            map.put("stuId",consultMerge.getStuId().toString());
            map.put("timeId",consultMerge.getTimeId().toString());
            map.put("isEnd",consultMerge.getIsEnd().toString());
            map.put("consultCount",consultMerge.getConsultCount().toString());
        } catch (Exception e){
            return map;
        }
//        map.put("consultantId",consultMerge.getConsultantId().toString());
//        map.put("startDate",consultMerge.getStartDate().toString());
//        map.put("endDate",consultMerge.getEndDate().toString());
        return map;
    }

    /**
     * 返回学生首页获取的咨询列表
     */
    @RequestMapping(value = "/getStuConsult",method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getStuConsult(Long stuId) throws Exception{
        List<ConsultMerge> consultMerges = consultMergeService.queryConsultMerge(stuId);
        List<Map<String,String>> resVisitLog = new ArrayList<>();
        for(ConsultMerge consultMerge:consultMerges){
            resVisitLog.add(packageConsult(consultMerge));
        }
        return JsonResponse.success(resVisitLog);
    }

    public Map<String,String> packageConsult(ConsultMerge consultMerge){
        Map<String,String> resMap = new HashMap<>();
        Date start_time = consultMerge.getStartDate();
        Calendar cal = Calendar.getInstance();
        cal.setTime(start_time);
        try{
            resMap.put("stu_name",userService.getById(consultMerge.getStuId()).getStuName());
            resMap.put("tea_name",userService.getById(consultMerge.getTeaId()).getStuName());
            resMap.put("start_time",new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
        }catch (Exception e){
            return resMap;
        }
        return resMap;
    }
}

